package cqrtplm.aop;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.log.TyplmLogger;
import com.hustcad.plm.caddocapi.service.TyplmCADDocumentService;
import com.hustcad.plm.pdm.folder.model.dto.HyperlinkDTO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderVO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderWebVO;
import com.hustcad.plm.pdm.folder.service.TyplmHyperlinkService;
import com.hustcad.plm.pdm.folder.service.TyplmSubFolderLinkService;
import com.hustcad.plm.pdm.middle.caddoc.model.dto.InsertCadDocDTO;
import com.ty.basic.entity.audit.AuditLogDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.utils.ArgumentUtils;
import cqrtplm.entity.ObjectStorageDO;
import cqrtplm.mapper.StoragePlanningMapper;
import cqrtplm.service.DocFolderOperationService;
import cqrtplm.service.ObjectStorageService;
import cqrtplm.vo.PDFProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;


@Aspect
@Component
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE)
public class CadDocCreateAOP {

    @Resource
    private TyplmLogger typlmLogger;

    @Resource
    private TyplmCADDocumentService typlmCADDocumentService;

    @Resource
    private StoragePlanningMapper storagePlanningMapper;

    @Resource
    private TyplmSubFolderLinkService typlmSubFolderLinkService;

    @Resource
    private DocFolderOperationService docFolderOperationService;

    @Resource
    private TyplmHyperlinkService typlmHyperlinkService;

    @Resource
    private ObjectStorageService objectStorageService;

    @Around(value = "execution(* com.hustcad.plm.middle.caddocapi.controller.TyplmCadDocumentController.createCadDoc(..))")
    public Object createCadDoc(ProceedingJoinPoint point) throws IOException {
        InsertCadDocDTO cadDocCreateDTO = (InsertCadDocDTO) point.getArgs()[0];
        boolean isCreateHyperlinks=false;
        InsertCadDocDTO cadDocCreateDTO2=null;

        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("属性异常");
        }
        HttpServletRequest request = attributes.getRequest();

        String displayName = (String) JSONObject.parseObject(request.getReader().readLine()).get("displayName");
        ObjectStorageDO objectStorageDO = objectStorageService.selectOneByTypeDefName(displayName);
        if (ObjectUtil.isEmpty(objectStorageDO) && StrUtil.isBlank(cadDocCreateDTO.getContainerType())){
            return ResponseResult.fail("400","类型："+cadDocCreateDTO.getTypeDefName()+"未维护对象存储映射");
        }

        if (StrUtil.isBlank(cadDocCreateDTO.getContainerType())){
            cadDocCreateDTO.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
        }

        if (cadDocCreateDTO.getContainerType().equals("ty.inteplm.product.CTyPDMLinkProduct")){

            if (ObjectUtil.isNotEmpty(objectStorageDO)){
                PDFProjectVO v = storagePlanningMapper.selectPdmIds(objectStorageDO.getContextName());

//                String cid = storagePlanningMapper.selectCabinetIdByOid(cadDocCreateDTO.getContainerId());
                String folderId = null;
                String[] split = objectStorageDO.getFolderPath().split("/");
                for (int i = 0; i < split.length; i++) {
                    String id=null;
                    if (StrUtil.isBlank(split[i])) {
                        continue;
                    }
                    if (i==1){
                        id= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                        split[i], "0");
                        if (StrUtil.isNotBlank(id)) {
                            folderId=id;
                        }
                    }else {
                        id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(), split[i], folderId);
                        if (StrUtil.isNotBlank(id)) {
                            folderId= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                  split[i], folderId);
                        }

                    }
                    if (StrUtil.isBlank(id)){
                        //创建文件夹
                        SubfolderVO subfolder=new SubfolderVO();
                        subfolder.setName(split[i]);
                        subfolder.setDescription("--系统自动创建--文件夹--");
                        subfolder.setParentOid(i==1?v.getDefaultcabinetoid():folderId);
                        subfolder.setParentOtype(i==1?"ty.inteplm.folder.CTyCabinet":"ty.inteplm.folder.CTySubFolder");
                        SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                        folderId=subfolderWebVO.getOid();
                    }
                }
                cadDocCreateDTO.setFolderId(folderId);
                cadDocCreateDTO.setContainerId(v.getOId());
                cadDocCreateDTO.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
            }
        }else if (cadDocCreateDTO.getContainerType().equals("ty.inteplm.project.CTyProject")){
            String xxx = storagePlanningMapper.queryExtendedAttributes(cadDocCreateDTO.getContainerId(), "密级");

            if (StrUtil.isNotBlank(xxx)&&xxx.equals("非密")){
                PDFProjectVO v = storagePlanningMapper.selectPdmIds(objectStorageDO.getContextName());
                if(ObjectUtil.isNotEmpty(v)){
                    isCreateHyperlinks=true;
                    cadDocCreateDTO2=new InsertCadDocDTO();
                    BeanUtil.copyProperties(cadDocCreateDTO, cadDocCreateDTO2);

                    cadDocCreateDTO.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
                    cadDocCreateDTO.setContainerId(v.getOId());

//                    String cid = v.getDefaultcabinetoid();
                    String folderId = null;
                    String[] split = objectStorageDO.getFolderPath().split("/");
                    for (int i = 0; i < split.length; i++) {
                        String id=null;
                        if (StrUtil.isBlank(split[i])) {
                            continue;
                        }
                        if (i==1){
                            id= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                            split[i], "0");
                            if (StrUtil.isNotBlank(id)) {
                                folderId=id;
                            }
                        }else {
                            id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(), split[i], folderId);
                            if (StrUtil.isNotBlank(id)) {
                                folderId= storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                      split[i], folderId);
                            }

                        }
                        if (StrUtil.isBlank(id)){
                            //创建文件夹
                            SubfolderVO subfolder=new SubfolderVO();
                            subfolder.setName(split[i]);
                            subfolder.setDescription("--系统自动创建--文件夹--");
                            subfolder.setParentOid(i==1?v.getDefaultcabinetoid():folderId);
                            subfolder.setParentOtype(i==1?"ty.inteplm.folder.CTyCabinet":"ty.inteplm.folder.CTySubFolder");
                            SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                            folderId=subfolderWebVO.getOid();
                        }
                    }
                    cadDocCreateDTO.setFolderId(folderId);
                }

            }
        }


        try {
            ArgumentUtils.checkArgumentEmpty(cadDocCreateDTO, "cadDocCreateDTO");
            cadDocCreateDTO.setName(StringUtils.trim(cadDocCreateDTO.getName()));
            cadDocCreateDTO.setNumber(StringUtils.trim(cadDocCreateDTO.getNumber()));
            String oid = this.typlmCADDocumentService.createCadDocByTemplate(cadDocCreateDTO);

            //是否创建超链接
            if (isCreateHyperlinks){
                HyperlinkDTO hyperlinkDTO =docFolderOperationService.assignmentToHyperlinkDTO(cadDocCreateDTO2,oid);
                List<HyperlinkDTO> l=new ArrayList<>();
                l.add(hyperlinkDTO);
                typlmHyperlinkService.batchCreateHyperlink(l);
            }
            return ResponseResult.success(oid);
        } catch (Exception var4) {
            AuditLogDO auditLogDO = new AuditLogDO();
            auditLogDO.setObjoid(BigInteger.ZERO);
            auditLogDO.setObjotype("ty.inteplm.cad.CTyCADDoc");
            auditLogDO.setContaineroidStr(cadDocCreateDTO.getContainerId());
            auditLogDO.setContainerotype(cadDocCreateDTO.getContainerType());
            auditLogDO.setTargettype(cadDocCreateDTO.getTypeDefName());
            auditLogDO.setTargetname(cadDocCreateDTO.getName());
            auditLogDO.setFolderpath(cadDocCreateDTO.getFolderPath());
            auditLogDO.setTargetnumber(cadDocCreateDTO.getNumber());
            auditLogDO.setTargetsecuritylabels(cadDocCreateDTO.getSecurityLabels());
            this.typlmLogger.errorInfo(LogEventEnum.CRATE_OBJECT, auditLogDO, var4);
            throw var4;
        }

    }
}
